#!/usr/local/python27
# coding=utf8


import urlparse
import time
import tornado.httpclient

import tornado.web
from mockserver.utils.log import logger



class ProxyHandler(tornado.web.RequestHandler):
    SUPPORTED_METHODS = ['GET', 'POST']
 
    def initialize(self, proxy_url="", **kwargs):
        self.proxy_url=proxy_url if urlparse.urlparse(proxy_url).path else urlparse.urljoin(proxy_url,self.request.uri)
    
        self.before_sleep=kwargs.get("before_sleep")
        self.after_sleep=kwargs.get("after_sleep")
        self.httpcode=kwargs.get("httpcode")
        logger.debug('Handle %s request to %s', self.request.method,self.proxy_url)
    def compute_etag(self):
        return None
 
    @tornado.web.asynchronous
    def get(self): 
        
        if self.before_sleep:
            logger.info("request sleep %s seconds",self.before_sleep)
            time.sleep(self.before_sleep)
            
        response = tornado.httpclient.HTTPRequest(
                                             url=self.proxy_url, 
                                             method='GET',
                                             headers=self.request.headers._dict,
                                             #body=self.request.arguments, 
                                             validate_cert=False)  
         
          
        client = tornado.httpclient.AsyncHTTPClient()
        client.fetch(response, self.deal, raise_error=False)
         
         
 
 
    @tornado.web.asynchronous
    def post(self):
        
        
        if self.before_sleep:
            logger.info("request sleep %s seconds",self.before_sleep)
            time.sleep(self.before_sleep)
        response = tornado.httpclient.HTTPRequest(
                                             url=self.proxy_url, 
                                             method='POST',
                                             headers=self.request.headers._dict,
                                             body=self.request.body,
                                             validate_cert=False)  
        client = tornado.httpclient.AsyncHTTPClient()
        client.fetch(response, self.deal, raise_error=False)
    
    #回调函数     
    def deal(self,response):
        if self.after_sleep:
            logger.info("response sleep %s seconds",self.after_sleep)
            time.sleep(self.after_sleep)
        if self.httpcode and self.httpcode <> 200:
            self.set_status(self.httpcode)
            self.finish()
        else:
            for key,value in  response.headers._dict.items():
                if key <> "Transfer-Encoding":
                    self.set_header(key,value) 
            logger.debug("Response is %s" ,response.body)  
            self.write(response.body)
            self.finish()            




